package com.legal.aid.app.service.impl;

import com.legal.aid.app.domain.dto.OrderAddDto;
import com.legal.aid.app.domain.dto.OrderUpdateDto;
import com.legal.aid.app.domain.vo.CommonUserVo;
import com.legal.aid.app.domain.vo.ConsultVo;
import com.legal.aid.app.domain.vo.LawyerDetailAppVo;
import com.legal.aid.app.domain.vo.OrderVo;
import com.legal.aid.app.mapper.AppConsultMapper;
import com.legal.aid.app.mapper.AppLawyerMapper;
import com.legal.aid.app.mapper.AppOrderMapper;
import com.legal.aid.app.mapper.AppUserMapper;
import com.legal.aid.app.service.IAppLawyerService;
import com.legal.aid.app.service.IAppOrderService;
import com.legal.aid.common.constant.CacheConstants;
import com.legal.aid.common.constant.OrderConstants;
import com.legal.aid.common.core.domain.entity.CommonUser;
import com.legal.aid.common.core.domain.model.AppLoginUser;
import com.legal.aid.common.core.redis.RedisCache;
import com.legal.aid.common.exception.user.UserNotLoginException;
import com.legal.aid.common.utils.DateUtils;
import com.legal.aid.common.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Random;

/**
 * 订单Service业务层处理
 *
 * @author doubao
 * @date 2025-05-27
 */
@Service
public class AppOrderServiceImpl implements IAppOrderService
{
    @Autowired
    private AppOrderMapper appOrderMapper;

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private AppConsultMapper appConsultMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AppLawyerMapper appLawyerMapper;


    /**
     * 查询订单列表
     *
     * @param orderVo 订单
     * @return 订单集合
     */
    @Override
    public List<OrderVo> selectOrderList(OrderVo orderVo)
    {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new UserNotLoginException();
        }
        orderVo.setUserId(commonUser.getId());
        return appOrderMapper.selectOrderList(orderVo);
    }

    /**
     * 新增订单
     *
     * @param orderAddDto 订单
     * @return 结果
     */
    @Override
    @Transactional
    public String insertOrder(OrderAddDto orderAddDto)
    {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new UserNotLoginException();
        }
        if(orderAddDto.getUserName().isEmpty()||orderAddDto.getUserName()==null){
            return OrderConstants.ORDER_USERNAME_NO_NULL;
        }
        if(orderAddDto.getLawyerId()==null){
            return OrderConstants.ORDER_LAWYER_Id_NO_NULL;
        }
        if(orderAddDto.getPhone().isEmpty()||orderAddDto.getPhone()==null){
            return OrderConstants.ORDER_PHONE_NO_NULL;
        }

        // 创建订单
        OrderVo orderVo = new OrderVo();
        Long lawyerId = orderAddDto.getLawyerId();

        // 复制基本属性
        BeanUtils.copyProperties(orderAddDto, orderVo);

        //设置价格
        orderVo.setPrice(orderAddDto.getPrice());

        // 设置用户ID
        orderVo.setUserId(commonUser.getId());

        // 设置创建时间
        orderVo.setCreateTime(DateUtils.getNowDate());

        //
        orderVo.setLawyerId(lawyerId);

        // 设置创建人
        orderVo.setCreatedBy(commonUser.getUserName());

        // 设置默认状态为待支付
        orderVo.setOrderStatus("0");

        // 设置默认删除状态为未删除
        orderVo.setIsDeleted("0");

        // 生成订单编号
        String orderNo = generateOrderNumber(commonUser.getId());
        orderVo.setOrderNo(orderNo);
        appOrderMapper.insertOrder(orderVo);

        //查询律师的userId
        LawyerDetailAppVo lawyerDetailByLawyerId = appLawyerMapper.getLawyerDetailByLawyerId(lawyerId.toString());

        updateChatList(commonUser.getId().toString(),lawyerDetailByLawyerId.getUserId().toString());

        //生成 咨询表
        ConsultVo consultVo = new ConsultVo();
        consultVo.setStatus("ongoing");
        consultVo.setIsDeleted("0");
        consultVo.setCreateTime(DateUtils.getNowDate());
        consultVo.setUserId(commonUser.getId());
        consultVo.setLawyerId(orderAddDto.getLawyerId());


        return appConsultMapper.insertConsult(consultVo)>0 ? orderNo : "0";
    }

    private void updateChatList(String userId, String partnerId) {
        String chatListKey = CacheConstants.CHAT_LIST_KEY + userId;

        // 1. 先移除已存在的对方ID（如果有）
        redisCache.removeFromList(chatListKey, 0, partnerId); // 移除所有匹配的元素

        // 2. 使用 LPUSH 将对方ID添加到列表头部
        redisCache.leftPush(chatListKey, partnerId);
    }
    /**
     * 订单编号生成   当前时间戳后8位，随机数4位，用户ID后4位
     * @param buyerId 买家ID
     * @return 订单编号
     */
    private String generateOrderNumber(long buyerId) {
        // 获取当前时间戳（毫秒）
        long timestamp = System.currentTimeMillis();

        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);

        // 处理买家ID，取后4位，不足补0
        String buyerIdStr = String.format("%04d", buyerId % 10000);

        // 组合：时间戳后8位 + 随机数4位 + 用户ID后4位
        String timestampStr = String.valueOf(timestamp).substring(5); // 取后8位
        String randomStr = String.format("%04d", randomNum);

        return timestampStr + randomStr + buyerIdStr;
    }

    /**
     * 修改订单
     *
     * @param orderUpdateDto 订单
     * @return 结果
     */
    @Override
    @Transactional
    public String updateOrder(OrderUpdateDto orderUpdateDto)
    {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new UserNotLoginException();
        }
        if(orderUpdateDto.getOrderNo().isEmpty()||orderUpdateDto.getOrderNo()==null){
            return OrderConstants.ORDER_NO_IS_NULL;
        }

        // 查询原订单信息
        OrderVo orderVo = appOrderMapper.selectOrderById(orderUpdateDto.getId());
        if (orderVo == null) {
            return OrderConstants.ORDER_NOT_EXIST;
        }
        // 检查是否为当前用户的订单
        if (!orderVo.getUserId().equals(commonUser.getId())) {
            return OrderConstants.ORDER_IS_NOT_YOU;
        }
        // 创建订单对象
        OrderVo updateOrder = new OrderVo();

        // 复制基本属性
        BeanUtils.copyProperties(orderUpdateDto, updateOrder);


        // 设置更新时间
        updateOrder.setUpdateTime(DateUtils.getNowDate());

        // 设置更新人
        updateOrder.setUpdatedBy(commonUser.getUserName());


        return appOrderMapper.updateOrder(updateOrder)>0 ? OrderConstants.ORDER_UPDATE_SUCCESS : "";
    }

    /**
     * 删除订单 可以批量
     *
     * @param ids 需要删除的订单主键集合
     * @return 结果
     */
    @Override
    @Transactional
    public String deleteOrderByIds(Long[] ids)
    {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new UserNotLoginException();
        }

        // 检查订单是否属于当前用户
        for (Long id : ids) {
            OrderVo order = appOrderMapper.selectOrderById(id);
            if (order == null) {
                return OrderConstants.ORDER_NOT_EXIST;
            }
            if (!order.getUserId().equals(appLoginUser.getUserId())) {
                return OrderConstants.ORDER_IS_NOT_YOU;
            }
        }

        return appOrderMapper.deleteOrderByIds(ids)>0 ? OrderConstants.ORDER_DELETE_SUCCESS : "";
    }

    /**
     * 获取订单详情
     * @param orderNo
     * @return
     */
    @Override
    public OrderVo selectOrderById(String orderNo) {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new RuntimeException("请先登录");
        }

        OrderVo orderVo = new OrderVo();
        orderVo.setUserId(commonUser.getId());
        orderVo.setOrderNo(orderNo);
        return  appOrderMapper.selectOrderList(orderVo).get(0);

    }


    /**
     * 支付订单
     */
    @Override
    @Transactional
    public String payOrder(String orderNo) {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new RuntimeException("请先登录");
        }

        OrderVo order = appOrderMapper.selectOrderByOrderNO(orderNo);

        // 校验订单
        validateOrder(order, commonUser.getId(), "0");

        //扣除钱包余额
        CommonUserVo user = appUserMapper.selectCommonUserById(commonUser.getId());
        if(user.getWalletBalance()<order.getPrice()){
            return OrderConstants.WALLETBALLANCE_ISENABLE;
        }
        int result=appUserMapper.deductWalletBalance(order.getPrice(), commonUser.getId());
        if(result==0){
            return OrderConstants.PAY_FAIL;
        }

        // 更新订单状态为已支付
        order.setOrderStatus("1"); // 1表示已支付
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdatedBy(commonUser.getUserName());
        appOrderMapper.updateOrder(order);

        return OrderConstants.PAY_SUCCESS;
    }

    /**
     * 取消订单
     */
    @Override
    @Transactional
    public int cancelOrder(String orderNO) {
        // 获取当前登录用户
        AppLoginUser appLoginUser = SecurityUtils.getAppLoginUser();
        CommonUser commonUser = appLoginUser.getCommonUser();
        if (commonUser == null) {
            throw new RuntimeException("请先登录");
        }

        // 查询订单信息
        OrderVo order = appOrderMapper.selectOrderByOrderNO(orderNO);

        // 校验订单
        validateOrder(order, commonUser.getId(), "0");

        // 更新订单状态为已取消
        order.setOrderStatus("2"); // 2表示已取消
        order.setUpdateTime(DateUtils.getNowDate());
        order.setUpdatedBy(commonUser.getUserName());

        return appOrderMapper.updateOrder(order);
    }

    /**
     * 校验订单信息
     * @param order 订单信息
     * @param userId 用户ID
     * @param allowedStatus 允许的状态
     */
    private void validateOrder(OrderVo order, Long userId, String allowedStatus) {
        // 检查订单是否存在
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 检查是否为当前用户的订单
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("订单不是自己的");
        }

        // 检查订单状态
        if (!allowedStatus.equals(order.getOrderStatus())) {
            throw new RuntimeException("订单状态不允许当前操作");
        }
    }

}
